#include "volumetool.h"
#include "ui_volumetool.h"
#include "QGraphicsDropShadowEffect"
#include "volumetool.h"
#include<QPainter>
#include<QDebug>
#include<QCursor>

VolumeTool::VolumeTool(QWidget *parent) :
    QWidget(parent),
    isMuted(false),
    volumeRatio(20),
    ui(new Ui::VolumeTool)
{
    ui->setupUi(this);
    setWindowFlags(Qt::Popup | Qt::FramelessWindowHint|
    Qt::NoDropShadowWindowHint);
    setAttribute(Qt::WA_TranslucentBackground);
    QGraphicsDropShadowEffect* shadowEffect = new
    QGraphicsDropShadowEffect(this);
    shadowEffect->setOffset(0, 0);
    shadowEffect->setColor("#646464");
    shadowEffect->setBlurRadius(5);
    setGraphicsEffect(shadowEffect);


    ui->silenceBtn->setIcon(QIcon(":/images/volumn.png"));

    ui->sliderBtn->move(ui->sliderBtn->x(),180-ui->silenceBtn->height()/2);

    ui->outSlider->setGeometry(ui->outSlider->x(),165,ui->outSlider->width(),150);
    ui->volumeRatio->setText("20%");






     connect(ui->silenceBtn,&QPushButton::clicked,this,&VolumeTool::onSilenceBtnCliced);
     ui->sliderBox->installEventFilter(this);

}

VolumeTool::~VolumeTool()
{
    delete ui;
}

void VolumeTool::paintEvent(QPaintEvent *event)
{
    (void)event;
    // 1. 创建绘图对象
    QPainter painter(this);
    // 2. 设置抗锯⻮
    painter.setRenderHint(QPainter::Antialiasing, true);
    // 3. 设置画笔
    // 没有画笔时：画出来的图形就没有边框和轮廓线
    painter.setPen(Qt::NoPen);
    // 4. 设置画刷颜⾊
    painter.setBrush(Qt::white);
    // 创建⼀个三⻆形
    QPolygon polygon;
    polygon.append(QPoint(10, 300+10));
    polygon.append(QPoint(10+80, 300+10));
    polygon.append(QPoint(10+40, 300+10+30));
    // 绘制三⻆形
    painter.drawPolygon(polygon);
    qDebug()<<"Paniter done";


}

void VolumeTool::onSilenceBtnCliced()
{
    isMuted=!isMuted;
    if(isMuted)
    {
        ui->silenceBtn->setIcon(QIcon(":/images/silent.png"));
    }
    else
    {
        ui->silenceBtn->setIcon(QIcon(":/images/volumn.png"));
    }
    emit setSilence(isMuted);
}

bool VolumeTool::eventFilter(QObject *object, QEvent *event)
{
   if(object ==ui->sliderBox)

   {

       if(event->type()==QEvent::MouseButtonPress)
       {

           setVolume();
       }else if(event->type()==QEvent::Wheel)
       {

           setVolume();
           emit setMusicVolume(volumeRatio);

       }else if(event->type()==QEvent::MouseButtonRelease)

       {
           emit setMusicVolume(volumeRatio);

       }
       return true;

   }

   return QObject::eventFilter(object,event);


}

void VolumeTool::setVolume()
{
  int height = ui->sliderBox->mapFromGlobal(QCursor().pos()).y();
  height=height<23? 23:height;
  height=height>203?203:height;

  ui->sliderBtn->move(ui->sliderBtn->x(),height-ui->silenceBtn->height()/3);

  ui->outSlider->setGeometry(ui->outSlider->x(),height,ui->outSlider->width(),203-height);

  volumeRatio=(int)((int)ui->outSlider->height()/(float)180*100);
  ui->volumeRatio->setText(QString::number(volumeRatio)+"%");
}
